layui.define(['layer', 'table'], function (exports) {
    var layer = layui.layer;
    var $ = layui.$;
    var table = layui.table;

    var utils = {
        parseUrlQuery: function (url) {
            var query = {};
            var urlToParse = url || window.location.href;
            var i;
            var params;
            var param;
            var length;
            if (typeof urlToParse === 'string' && urlToParse.length) {
                urlToParse = urlToParse.indexOf('?') > -1 ? urlToParse.replace(/\S*\?/, '') : '';
                params = urlToParse.split('&').filter(paramsPart => paramsPart !== '');
                length = params.length;

                for (i = 0; i < length; i += 1) {
                    param = params[i].replace(/#\S+/g, '').split('=');
                    query[decodeURIComponent(param[0])] = typeof param[1] === 'undefined' ? undefined : decodeURIComponent(param.slice(1).join('=')) || '';
                }
            }
            return query;
        },
        parseRouterQuery: function () {
            var currentUrl = ''
            var url = window.location.href
            if (url.indexOf("#") > -1) {
                currentUrl = url.split('#')[1]
            } else {
                currentUrl = url
            }
            return this.parseUrlQuery(currentUrl);
        },
        addQueryToUrlNoRefresh: function (query, isSetHistory) {
            var hash = window.location.hash
            var url = location.origin + location.pathname + location.search
            if (hash) {
                if (hash.indexOf('?') > -1) {
                    hash = hash.split('?')[0]
                }
                url += hash
            }
            var hashSearch = ''
            var hashSearchArr = []
            if (query) {
                for (var key in query) {
                    if (query.hasOwnProperty(key)) {
                        hashSearchArr.push(key + '=' + query[key])
                    }
                }
                hashSearch = '?' + hashSearchArr.join('&')
            }
            url += hashSearch
            if (isSetHistory) {
                window.history.pushState(null, '', url)
            } else {
                window.history.replaceState(null, '', url)
            }
        },
        generateUUID: function () {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
                var r = Math.random() * 16 | 0;
                var v = c === 'x' ? r : ((r & 0x3) | 0x8);
                return v.toString(16);
            });
        },
        copyObject: function (toObj, fromObj) {
            if (toObj && fromObj) {
                for (var key in fromObj) {
                    if (fromObj.hasOwnProperty(key)) {
                        toObj[key] = fromObj[key]
                    }
                }
            }
        },
        copySelfObject: function (toObj, fromObj) {
            if (toObj && fromObj) {
                for (var key in toObj) {
                    if (toObj.hasOwnProperty(key) && fromObj[key]) {
                        toObj[key] = fromObj[key]
                    }
                }
            }
        },
        copyObjectWithIgnoreKey: function (toObj, fromObj, ignoreKey) {
            if (toObj && fromObj && Array.isArray(ignoreKey)) {
                for (var key in fromObj) {
                    if (fromObj.hasOwnProperty(key) && ignoreKey.indexOf(key) === -1) {
                        toObj[key] = fromObj[key]
                    }
                }
            }
        },
        dataDelete: function (id, list) {
            for (var index = 0; index < list.length; index++) {
                if (list[index].id === id) {
                    list.splice(index, 1);
                    return
                }
            }
        },
        Ajax: function (config) {
            if (config.showLoading) {
                //TODO: 显示layer的loading
            }
            var headers = {"token": sessionStorage.getItem("token")}; //传token之类的

            $.ajax({
                url: config.url,
                dataType: config.dataType,
                type: config.type,
                // contentType: config.contentType || 'application/json',
                data: config.data,
                headers: headers,
                success: function (response) {
                    if (response.code == 200) {
                        if (typeof config.success === 'function') {
                            config.success(response)
                        }
                    } else {
                        layer.msg(response.message);
                    }
                },
                error: function (err) {
                    layer.msg('请求错误！');
                    if (typeof config.error === 'function') {
                        config.error(err)
                    }
                },
                complete: function () {
                    // TODO： 隐藏layer的laoding

                    if (typeof config.complete === 'function') {
                        config.complete()
                    }
                }
            })
        },
        dropdown: function (options) {
            var el = options.el ? options.el : '.layui-dropdown';
            var toggle = '.layui-dropdown-toggle';
            var event = options.trigger === 'click' ? 'click' : 'mouseenter';

            var $el = $(el).eq(0);
            var $elem = $el.find(toggle);
            var $elemContent = $el.children('.layui-dropdown-content');
            var isR = $el.hasClass('dropdown-right');
            var timer = '';

            $elemContent.css('z-index', options.zIndex);
            $elemContent.addClass('layui-anim layui-anim-upbit');

            $el.parents().on('mouseenter', function (e) {
                e.stopPropagation();
            });
            $elem.on(event, function (e) {
                var disabled = $elem.hasClass('layui-btn-disabled');
                if (disabled) return;
                clearTimeout(timer);
                // var overHeight = ($elem.offset().top + $elem.height() + ulBox.outerHeight() - $(window).scrollTop()) > $(window).height();
                // overHeight ?  $elemContent.css({"top":"auto","bottom":"100%"}) : $elemContent.css({"top":"100%","bottom":"auto"});
                // 计算偏移量
                var elemW = $elem.innerWidth();
                var elemH = $elem.innerHeight();
                var elemPos = $elem.position();
                var elemContentW = $elemContent.innerWidth();
                var elemPosTop = elemPos.top;
                var elemPosLeft = elemPos.left;

                $elemContent.css({"top": elemPosTop + elemH, "left": elemPosLeft - (isR ? elemContentW - elemW : 0)});

                $elemContent.show(0, function () {
                    if (typeof options.onShow === 'function') {
                        options.onShow($el)
                    }
                });
            });
            // $elemContent.on(event, function (e) {
            //     e.stopPropagation();
            //     e.preventDefault();
            // });
            if (event == 'mouseenter') {
                $el.on("mouseleave", function (e) {
                    timer = setTimeout(function () {
                        $elemContent.hide();
                    }, 300);
                })
            } else {
                $(document).on("mouseup", function (e) {
                    var userSet_con = $el;
                    if (!userSet_con.is(e.target) && userSet_con.has(e.target).length === 0) {
                        $elemContent.hide()
                    }
                });
            }

            if ($el.parents('.layui-table-cell')) {
                $el.parents('.layui-table-cell').addClass('layui-visible');
            }
        },
        sideFold: function () {
            $('.left-nav-tool').click(function () {
                var $this = $(this);
                var $fa= $this.find('.fa');
                if($fa.attr('data-fold') == 0) {
                    $fa.addClass('fa-indent').removeClass('fa-outdent');
                    $fa.attr("data-fold", 1);
                    $('body').addClass('hide-left-menu');
                    setTimeout(function() {
                        $(window).trigger('resize')
                    }, 200)
                } else {
                    $fa.addClass('fa-outdent').removeClass('fa-indent');
                    $fa.attr("data-fold", 0);
                    $('body').removeClass('hide-left-menu');
                    setTimeout(function() {
                        $(window).trigger('resize')
                    }, 200)
                }
            })
        },
        dataToTree: function (a, idStr, pidStr, childrenStr) {
            var r = [], hash = {}, id = idStr || 'id', pid = pidStr || 'parentId', children = childrenStr || 'children', i = 0, j = 0, len = a.length;
            for (; i < len; i++) {
                hash[a[i][id]] = a[i];
            }
            for (; j < len; j++) {
                var aVal = a[j], hashVP = hash[aVal[pid]];
                if (hashVP) {
                    !hashVP[children] && (hashVP[children] = []);
                    hashVP[children].push(aVal);
                } else {
                    r.push(aVal);
                }
            }
            return r;
        }
    }
    exports('utils', utils);
})
